package dnspod

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"

	"github.com/antonholmquist/jason"
)

func (c Client) request(api string, params url.Values) (*http.Response, error) {
	params.Set("login_token", c.id+","+c.token)
	params.Set("format", "json")
	resp, err := http.Post("https://dnsapi.cn/"+api,
		"application/x-www-form-urlencoded", strings.NewReader(params.Encode()))
	if err != nil {
		return nil, err
	}
	//data, _ := ioutil.ReadAll(resp.Body)
	//fmt.Println(string(data))
	if resp.StatusCode != http.StatusOK {
		data, _ := ioutil.ReadAll(resp.Body)
		resp.Body.Close()
		return nil, fmt.Errorf("%s call failed, http_code=%d\n%s",
			api, resp.StatusCode, string(data))
	}
	return resp, nil
}

func (c Client) list(api string, params url.Values, cb func(*jason.Object) (int, bool)) (e error) {
	defer func() {
		if err := recover(); err != nil {
			e = err.(error)
		}
	}()
	var offset int
	params.Set("length", "20")
	for {
		if !func() bool {
			params.Set("offset", fmt.Sprintf("%d", offset))
			resp, err := c.request(api, params)
			assert(err)
			defer resp.Body.Close()
			obj, err := jason.NewObjectFromReader(resp.Body)
			assert(err)
			cnt, next := cb(obj)
			offset += cnt
			return next
		}() {
			return nil
		}
	}
}
